#!/usr/bin/python
#Test and demonstration of DistNumPy.
import sys
import os
import getopt
import subprocess

OUTPUT_PARSER = "dndoutput.py"
TmpDir = os.path.join("/","tmp")
T1 = os.path.join(TmpDir, "dndnumpy_t1.csv")
T1s = os.path.join(TmpDir, "dndnumpy_t1s.csv")
T2 = os.path.join(TmpDir, "dndnumpy_t2.csv")
T2s = os.path.join(TmpDir, "dndnumpy_t2s.csv")


if __name__ == "__main__":
    blocking = ""
    latencyhiding = ""
    gnuplot_src = os.path.join(TmpDir, "dndnumpy_gnuplot.src")
    output = ""
    smp = False

    try:
        opts, args = getopt.getopt(sys.argv[1:],"b:l:o:S",["blocking=", "latency-hiding=", "output=", "smp"])
    except getopt.GetoptError, err:
        print str(err)
        sys.exit(2)
    for o, a in opts:
        if o in ("-b", "--blocking"):
            blocking = a
        elif o in ("-l", "--latency-hiding"):
            latencyhiding = a
        elif o in ("-o", "--output"):
            output = a
        elif o in ("-S","--smp"):
            smp = True
        else:
            assert False, "unhandled option"
    assert latencyhiding != "", "the latency-hiding directory is not specified"

    # Write the csv files generated by the OUTPUT_PARSER.
    if not smp:
        assert blocking != "" or smp, "the blocking directory not specified"
        f = open(T1, "w")
        subprocess.Popen([OUTPUT_PARSER, "numpy", blocking], stdout=f).wait()
        f.close()
        #f = open(T1s, "w")
        #subprocess.Popen([OUTPUT_PARSER, "dnumpy", blocking], stdout=f).wait()
        #f.close()
    f = open(T2, "w")
    subprocess.Popen([OUTPUT_PARSER, "numpy", latencyhiding], stdout=f).wait()
    f.close()
    #f = open(T2s, "w")
    #subprocess.Popen([OUTPUT_PARSER, "dnumpy", latencyhiding], stdout=f).wait()
    #f.close()

    # Write the GnuPlot source file.
    if smp:
        gnuplot = """### Generated by dndgraph.py ###
        reset
        set encoding iso_8859_1
        #set title "Strong scaling of Test."
        set xlabel 'No. of CPU-cores'
        set ylabel 'Speedup of DistNumPy compared to NumPy'
        #set xrange [1:128]
        set yrange [2:40]
        set key left top
        set grid ytic
        set ytics (1,2,4,8,16,32,64,128)
        set datafile separator ";"
        set log y
        """
        gnuplot += "set terminal postscript \n set output  '%s' \n"%output
        gnuplot += "plot '%s' using 2:xticlabels(1) axis x1y1 with linespoints lw 4 title 'By Node',"%T2
        gnuplot += "'%s' using 4:xticlabels(1) axis x1y1 with linespoints lw 4 title 'By Core'\n"%T2
    else:
        gnuplot = """### Generated by dndgraph.py ###
        reset
        set encoding iso_8859_1
        #set title "Strong scaling of Test."
        set xlabel 'No. of CPU-cores'
        set ylabel 'Speedup of DistNumPy compared to NumPy'
        set y2label 'Relative waiting time in percentage of total time'
        #set xrange [1:128]
        #set yrange [2:32]
        set y2range [0:100]
        set key left top
        set grid ytic
        set ytics (1,2,4,8,16,32,64,128)
        set datafile separator ";"
        set ytics nomirror
        set y2tics
        set log y
        """
        gnuplot += "set style data histograms\n"
        gnuplot += "set style fill pattern 1.0 border\n"
        gnuplot += "plot '%s' using 3 axis x1y2 title 'Blocking (waiting time)', '%s' using 3 axis x1y2 title 'Latency-Hiding (waiting time)'\n"%(T1,T2)
        gnuplot += "set terminal postscript \n set output  '%s' \n"%output
        gnuplot += "replot '%s' using 2:xticlabels(1) axis x1y1 with linespoints lw 4 title 'Blocking (speedup)',"%T1
        gnuplot += "'%s' using 2:xticlabels(1) axis x1y1 with linespoints lw 4 title 'Latency-Hiding (speedup)'\n"%T2
        #gnuplot += "'%s' using 2:xticlabels(1) axis x1y1 with linespoints lw 4 title 'Blocking (speedup of DistNumPy)',"%T1s
        #gnuplot += "'%s' using 2:xticlabels(1) axis x1y1 with linespoints lw 4 title 'Latency-Hiding (speedup of DistNumPy)'\n"%T2s

    if output == "":# we just return the gnuplot source output.
        print gnuplot
    else:
        f = open(gnuplot_src, "w")
        f.write(gnuplot)
        f.close()
        subprocess.call(["gnuplot",gnuplot_src])




